package com.jp.knowledge.view;

import android.content.Context;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.RotateAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.google.gson.JsonObject;
import com.jiayen.cache.FileCacheManager;
import com.jp.knowledge.R;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.model.PopularSearchModel;
import com.jp.knowledge.util.ResultSubscriber;

import java.util.ArrayList;
import java.util.List;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by 528787067@qq.com on 2017/3/14.
 */

public class HomePagePopularSearches extends FrameLayout implements View.OnClickListener, ResultSubscriber.OnResultListener {

    private long WORD_SWITCH_TIME = 5000;
    private long ANIMATION_DURATION_TIME = 800;

    private Context context;
    private FlowLayout flowLayout;
    private ViewFlipper popularSearchWordShowView;
    private LinearLayout switchWordBtn;
    private ImageView switchWordBtnIcon;

    private int page;
    private List<PopularSearchModel> popularSearchModels;
    private OnClickListener popularSearchListener;

    private FileCacheManager cacheManager;
    private String popularWordCachePath;
    private Observable.OnSubscribe<List<PopularSearchModel>> readCacheOnSubscribe;
    private Subscriber<List<PopularSearchModel>> readCacheSubscribe;
    private Animation animation;

    public HomePagePopularSearches(Context context) {
        super(context);
        init();
    }

    public HomePagePopularSearches(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public HomePagePopularSearches(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init(){
        context = getContext();

        page = 0;
        popularSearchModels = new ArrayList<>();
        initCache();

        View contentView = View.inflate(context, R.layout.home_page_popular_searches_view, this);
        flowLayout = (FlowLayout) contentView.findViewById(R.id.flowLayout);
        popularSearchWordShowView = (ViewFlipper) contentView.findViewById(R.id.popular_search_word_show_view);
        switchWordBtn = (LinearLayout) contentView.findViewById(R.id.popular_search_switch_btn);
        switchWordBtnIcon = (ImageView) contentView.findViewById(R.id.popular_search_switch_iocn);
        switchWordBtn.setOnClickListener(this);
        popularSearchWordShowView.setAutoStart(true);
        popularSearchWordShowView.setFlipInterval((int) WORD_SWITCH_TIME);
        popularSearchWordShowView.setInAnimation(AnimationUtils.loadAnimation(context, R.anim.slide_bottom_in));
        popularSearchWordShowView.setOutAnimation(AnimationUtils.loadAnimation(context, R.anim.slide_top_out));

        popularSearchListener = new OnClickListener() {
            @Override
            public void onClick(View v) {
                PopularSearchModel popularSearchModel = (PopularSearchModel) v.getTag();
//                SearchActivity.gotoSearch(context, popularSearchModel.getTagName(), 0);

            }
        };

        readPopularSearchWords();
    }

    private void initCache(){
        cacheManager = new FileCacheManager();
        popularWordCachePath = context.getCacheDir()+"/popularSearch_" + HttpHelper.uuid + ".dat";
        readCacheOnSubscribe = new Observable.OnSubscribe<List<PopularSearchModel>>() {
            @Override
            public void call(Subscriber<? super List<PopularSearchModel>> subscriber) {
                List<PopularSearchModel> appData = (List<PopularSearchModel>) cacheManager.readObject(popularWordCachePath);
                subscriber.onNext(appData);
            }
        };
        readCacheSubscribe = new Subscriber<List<PopularSearchModel>>() {
            @Override
            public void onCompleted() {
                getPopularSearch(++page);
            }
            @Override
            public void onError(Throwable e) {
                onCompleted();
            }
            @Override
            public void onNext(List<PopularSearchModel> data) {
                setFlowLayout(data);
                onCompleted();
            }
        };
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.popular_search_switch_btn) {
            getPopularSearch(++page);
        }
    }

    /* TODO 该函数有待优化 */
    private void setFlowLayout(final List<PopularSearchModel> popularSearchModels){
        flowLayout.removeAllViews();
        for(PopularSearchModel popularSearchModel : popularSearchModels){
            TextView popularSearchText = new TextView(context);
            popularSearchText.setTextSize(TypedValue.COMPLEX_UNIT_PX, context.getResources().getDimension(R.dimen.min_font_12));
            popularSearchText.setText(popularSearchModel.getTagName());
            popularSearchText.setPadding((int)getResources().getDimension(R.dimen.space_min_super), 0,
                    (int)getResources().getDimension(R.dimen.space_min_super), 0);
            flowLayout.addView(popularSearchText);
        }
        flowLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                List<List<View>> popularSearchViews = new ArrayList<>();
                for(int i = 0, j = flowLayout.getLineNums(); i < j; i++)
                    popularSearchViews.add(flowLayout.getLineView(i));
                if(flowLayout.getLineNums() == 0)
                    return;
                popularSearchWordShowView.stopFlipping();
                flowLayout.removeAllViews();
                popularSearchWordShowView.removeAllViews();
                try {
                    for(int i = 0, k = 0; i < popularSearchViews.size(); i++){
                        LinearLayout lineLayout = new LinearLayout(context);
                        lineLayout.setOrientation(LinearLayout.HORIZONTAL);
                        lineLayout.setGravity(Gravity.CENTER_VERTICAL);
                        for(int j = 0; j < popularSearchViews.get(i).size(); j++){
                            TextView popularSearchText = new TextView(context);
                            popularSearchText.setTextColor(context.getResources().getColor(R.color.font_gray_deep));
                            popularSearchText.setTextSize(TypedValue.COMPLEX_UNIT_PX, context.getResources().getDimension(R.dimen.min_font_12));
                            popularSearchText.setText(popularSearchModels.get(k).getTagName());
                            popularSearchText.setTag(popularSearchModels.get(k++));
                            popularSearchText.setPadding((int)getResources().getDimension(R.dimen.space_min_super), 0,
                                    (int)getResources().getDimension(R.dimen.space_min_super), 0);
                            popularSearchText.setOnClickListener(popularSearchListener);
                            lineLayout.addView(popularSearchText);
                        }
                        popularSearchWordShowView.addView(lineLayout);
                    }
                } catch (Exception e){} finally {
                    popularSearchWordShowView.startFlipping();
                }
            }
        });
    }

    private void savePopularSearchWords(final List<PopularSearchModel> popularSearchModels){
        new Thread(new Runnable() {
            @Override
            public void run() {
                cacheManager.wirteObject(popularSearchModels, popularWordCachePath);
            }
        }).start();
    }

    private void readPopularSearchWords(){
        Observable.create(readCacheOnSubscribe)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(readCacheSubscribe);
    }

    private void getPopularSearch(int page){
        JsonObject param = new JsonObject();
        param.addProperty("token", HttpHelper.token);
        param.addProperty("page", page);
        param.addProperty("type", 0);
        param.addProperty("recommendAction", 1);
        param.addProperty("action", 1);
        HttpHelper.getInstance(context).hotSearch(param, page, this);
    }

    public void refreshPopularSearch(){
        getPopularSearch(++page);
    }

    private long startTime;
    private long endTime;
    @Override
    public void onStart(int requestType) {
        startTime = System.currentTimeMillis();
        if(animation == null) {
            animation = new RotateAnimation(0, 360,
                    switchWordBtnIcon.getWidth() / 2,
                    switchWordBtnIcon.getHeight() / 2);
            animation.setDuration(ANIMATION_DURATION_TIME);
            animation.setRepeatMode(Animation.RESTART);
            animation.setRepeatCount(Animation.INFINITE);
        }
        switchWordBtnIcon.clearAnimation();
        switchWordBtnIcon.startAnimation(animation);
    }
    @Override
    public void onCompleted(int requestType) {
        endTime = System.currentTimeMillis();
        if(endTime - startTime >= ANIMATION_DURATION_TIME) {
            switchWordBtnIcon.clearAnimation();
        } else{
            switchWordBtnIcon.postDelayed(new Runnable() {
                @Override
                public void run() {
                    switchWordBtnIcon.clearAnimation();
                }
            }, ANIMATION_DURATION_TIME - (endTime - startTime));
        }
    }
    @Override
    public void onError(int requestType) {
        onCompleted(requestType);
    }
    @Override
    public void onNext(IModel data, int requestType) {
        if(data.getErrcode() != 0){
            onError(requestType);
        } else{
            List<PopularSearchModel> popularSearchModelList = data.getList(PopularSearchModel.class);
//            if(requestType == 1)
                popularSearchModels.clear();
            if(popularSearchModelList != null && popularSearchModelList.size() > 0)
                popularSearchModels.addAll(popularSearchModelList);
            setFlowLayout(popularSearchModels);
            savePopularSearchWords(popularSearchModels);
        }
    }
}
